package com.kylin.module.shop.actions;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.hibernate.criterion.Order;


import com.kylin.common.Constants;
import com.kylin.common.entity.MsgKey;
import com.kylin.common.exception.BusinessException;
import com.kylin.common.paginate.DisplayPage;
import com.kylin.common.paginate.PageManager;
import com.kylin.hibernate.CriteriaInfo;
import com.kylin.hibernate.PropertyCondition;
import com.kylin.module.baseapp.business.BaseBlogic;
import com.kylin.module.shop.business.CompanyBlogic;
import com.kylin.module.shop.forms.CompanyForm;
import com.kylin.module.shop.orm.Advisory;
import com.kylin.module.shop.orm.Company;
import com.kylin.module.shop.orm.Product;
import com.kylin.struts.BaseDispatchAction;

public class CompanyAction extends BaseDispatchAction {

	protected static Logger log = Logger.getLogger(CompanyAction.class);
	
	/**
	 * 企业说明信息修改
	 * @param mapping
	 * @param actionForm
	 * @param request
	 * @param response
	 * @return
	 */
	public ActionForward doManage1(ActionMapping mapping, ActionForm actionForm, HttpServletRequest request, HttpServletResponse response) {
		log.debug("企业说明信息修改");
		String forward = "manage1";
		CompanyForm form = (CompanyForm) actionForm;
		try{
			Company currCom = (Company)request.getSession().getAttribute(Constants.CURR_LANG_COMPANY);
			form.setLanguage(getSessionLocale(request).toString());
			CompanyBlogic blogic = new CompanyBlogic();
			currCom = blogic.updateCompany(form);
			log.info("企业说明信息修改成功："+ form.getName());
			request.getSession().setAttribute(Constants.CURR_LANG_COMPANY,currCom);
			request.setAttribute(Constants.MSGKEY, new MsgKey("","信息修改成功"));
			request.getSession().setAttribute(Constants.CURR_USER, blogic.getLoginUser(currCom.getUser().getUsername(),getLocale(request).toString()));
		}catch (Exception e) {
			forward = doException( request, e,forward);
		}
		
		return mapping.findForward(forward);
	}
	
	public ActionForward manage2(ActionMapping mapping, ActionForm actionForm, HttpServletRequest request, HttpServletResponse response) {
		log.debug("填写新产品");
		return mapping.findForward("manage2");
	}
	
	public ActionForward manage3(ActionMapping mapping, ActionForm actionForm, HttpServletRequest request, HttpServletResponse response) {
		log.debug("查看展示区 : "+request.getParameter("searchId"));
		String forward = "manage3";
		int pageSize = 10;// 分页列表的每页行数  
		int pageNum = 1;
		String searchId = request.getParameter("searchId");
		CriteriaInfo cinfo = null;
		try {
			if (request.getParameter("page") != null) {
				pageNum = Integer.parseInt(request.getParameter("page"));
			}
			Company currCom = (Company)request.getSession().getAttribute(Constants.CURR_LANG_COMPANY);
			if (searchId == null) {
				PropertyCondition[] pConditions = new PropertyCondition[] {
						// 条件： Product.company = currCom
						new PropertyCondition("company", currCom,PropertyCondition.OPERATOR_EQ ),
						// 条件： Product.active = 1
						new PropertyCondition("language", this.getSessionLocale(request).toString(),PropertyCondition.OPERATOR_EQ ),
						new PropertyCondition("active", Product.ACTIVE_SHOW,PropertyCondition.OPERATOR_EQ )
				};
				// 将查询条件保存在 CriteriaInfo，加入到用户缓存UserCache,这样翻页查询时不用再次传入条件
				cinfo = new CriteriaInfo(Product.class, pConditions, Order.asc("createdon"));
				searchId = this.addUserCacheCriteriaInfo(request, cinfo);
				request.setAttribute(Constants.KEY_REQUEST_QUERYID, searchId);
			}
			cinfo = getUserCacheCriteriaInfo(request, searchId);
			CompanyBlogic blogic = new CompanyBlogic();
			DisplayPage page = blogic.getProductList(pageSize,pageNum, cinfo);
			request.setAttribute(Constants.KEY_REQUEST_RESULT, page);			
		}catch (Exception e) {
			forward = doException( request, e,forward);
		}
		
		return mapping.findForward(forward);
	}
	
  
	public ActionForward add(ActionMapping mapping, ActionForm actionForm, HttpServletRequest request, HttpServletResponse response) {
		return null;
	}
	
	public ActionForward manage4(ActionMapping mapping, ActionForm actionForm, HttpServletRequest request, HttpServletResponse response) {
		log.debug("查看产品库 : ");
		String forward = "manage4";
		int pageSize = 10;// 分页列表的每页行数  
		int pageNum = 1;
		String searchId = request.getParameter("searchId");
		CriteriaInfo cinfo = null;
		try {
			if (request.getParameter("page") != null) {
				pageNum = Integer.parseInt(request.getParameter("page"));
			}
			Company currCom = (Company)request.getSession().getAttribute(Constants.CURR_LANG_COMPANY);
			if (searchId == null) {
				System.out.println("第一次构造条件");
				List conds = new LinkedList();
				// 条件： Product.company = currCom
				conds.add(new PropertyCondition("company", currCom,PropertyCondition.OPERATOR_EQ ));
				// 条件： Product.language = language
				//conds.add(new PropertyCondition("language", this.getSessionLocale(request).toString(),PropertyCondition.OPERATOR_EQ ));
				// 条件： Product.active = 2
				conds.add(new PropertyCondition("active", Product.ACTIVE_INDB,PropertyCondition.OPERATOR_EQ ));
				if(request.getParameter("name") != null && !request.getParameter("name").equals("")){
					String likeExp = "%"+request.getParameter("name")+"%";
//					 条件： Product.name like '%xxx%'
					conds.add(new PropertyCondition("name",likeExp,PropertyCondition.OPERATOR_LIKE));
				}
				if(request.getParameter("name") != null && !request.getParameter("name").equals("")){
					String likeExp = "%"+request.getParameter("name")+"%";
//					 条件： Product.name like '%xxx%'
					conds.add(new PropertyCondition("name",likeExp,PropertyCondition.OPERATOR_LIKE));
				}
				PropertyCondition[] condArray = (PropertyCondition[])conds.toArray(new PropertyCondition[0]);	
				// 将查询条件保存在 CriteriaInfo，加入到用户缓存UserCache,这样翻页查询时不用再次传入条件
				cinfo = new CriteriaInfo(Product.class, condArray, Order.asc("createdon"));
				searchId = this.addUserCacheCriteriaInfo(request, cinfo);
				request.setAttribute(Constants.KEY_REQUEST_QUERYID, searchId);
			}else{
				System.out.println("使用用户缓存中的cinfo="+getUserCacheCriteriaInfo(request, searchId));
			}
			cinfo = getUserCacheCriteriaInfo(request, searchId);
			CompanyBlogic blogic = new CompanyBlogic();
			DisplayPage page = blogic.getProductList(pageSize,pageNum, cinfo);
			request.setAttribute(Constants.KEY_REQUEST_RESULT, page);
			
		}catch (Exception e) {
			forward = doException( request, e,forward);
		}
		return mapping.findForward(forward);
 
	}

	
	public ActionForward manage5(ActionMapping mapping, ActionForm actionForm, HttpServletRequest request, HttpServletResponse response) {
		log.debug("查询订单");
		String forward = "manage5";
		int pageSize = 10;// 分页列表的每页行数  
		int pageNum = 1;
		String searchId = request.getParameter("searchId");
		CriteriaInfo cinfo = null;
		try {
			if (request.getParameter("page") != null) {
				pageNum = Integer.parseInt(request.getParameter("page"));
			}
			Company currCom = (Company)request.getSession().getAttribute(Constants.CURR_LANG_COMPANY);
			if (searchId == null) {
				System.out.println("第一次构造条件");
				List conds = new LinkedList();
				// 条件： Order.company = currCom
				conds.add(new PropertyCondition("product.company", currCom,PropertyCondition.OPERATOR_EQ ));
				
				if(request.getParameter("active") != null && !request.getParameter("active").equals("")){
					// 条件： active = 2
					conds.add(new PropertyCondition("active",new Short(request.getParameter("active")) ,PropertyCondition.OPERATOR_EQ ));
				}
				if(request.getParameter("start") != null && !request.getParameter("start").equals("")){
					Date start = new SimpleDateFormat("yyyy-MM-dd").parse(request.getParameter("start"));
					//条件： createdon >= 2007-12-03
					conds.add(new PropertyCondition("createdon",start,PropertyCondition.OPERATOR_GE));
				}
				if(request.getParameter("end") != null && !request.getParameter("end").equals("")){
					Date end = new SimpleDateFormat("yyyy-MM-dd").parse(request.getParameter("end"));
					//条件： createdon <= 2007-12-03
					conds.add(new PropertyCondition("createdon",end,PropertyCondition.OPERATOR_LE));
				}
//				if(request.getParameter("productName") != null && !request.getParameter("productName").equals("")){
//					String likeExp = "%"+request.getParameter("productName")+"%";
//					// 条件： Product.name like '%xxx%'
//					conds.add(new PropertyCondition("product.name",likeExp,PropertyCondition.OPERATOR_LIKE));
//				}
				PropertyCondition[] condArray = (PropertyCondition[])conds.toArray(new PropertyCondition[0]);	
				// 将查询条件保存在 CriteriaInfo，加入到用户缓存UserCache,这样翻页查询时不用再次传入条件
				cinfo = new CriteriaInfo(com.kylin.module.shop.orm.Order.class, condArray, Order.asc("createdon"));
				searchId = this.addUserCacheCriteriaInfo(request, cinfo);
				request.setAttribute(Constants.KEY_REQUEST_QUERYID, searchId);
			}else{
				System.out.println("使用用户缓存中的cinfo="+getUserCacheCriteriaInfo(request, searchId));
			}
			cinfo = getUserCacheCriteriaInfo(request, searchId);
			DisplayPage page =  PageManager.getDisplayPage(pageSize, pageNum, cinfo);
			request.setAttribute(Constants.KEY_REQUEST_RESULT, page);
			
		}catch (Exception e) {
			forward = doException( request, e,forward);
		}
		return mapping.findForward(forward);
	}
	
	public ActionForward manage6(ActionMapping mapping, ActionForm actionForm, HttpServletRequest request, HttpServletResponse response) {
		log.debug("发布贸易信息");
		return mapping.findForward("manage6");
	}
	
	/**
	 * 查询咨询信息
	 * @param mapping
	 * @param actionForm
	 * @param request
	 * @param response
	 * @return
	 */
	public ActionForward manage7(ActionMapping mapping, ActionForm actionForm, HttpServletRequest request, HttpServletResponse response) {
		log.debug("查询咨询信息");
		String forward = "manage7";
		int pageSize = 20;// 分页列表的每页行数  
		int pageNum = 1;  // 当前页号

		CriteriaInfo cinfo = null;
		try {
			if (request.getParameter("page") != null) {
				pageNum = Integer.parseInt(request.getParameter("page"));
			}
			Company currCom = (Company)request.getSession().getAttribute(Constants.CURR_LANG_COMPANY);
			if(currCom == null)
				throw new BusinessException("长时间未刷新页面，登录信息已失效，请重登录");
		    PropertyCondition[] conds = new PropertyCondition[]{
		    		new PropertyCondition("company",currCom,PropertyCondition.OPERATOR_EQ )
		    };

			// 将查询条件保存在 CriteriaInfo，加入到用户缓存UserCache,这样翻页查询时不用再次传入条件
			cinfo = new CriteriaInfo(Advisory.class, conds, Order.desc("createdon"));
			DisplayPage page = PageManager.getDisplayPage(pageSize, pageNum, cinfo);
			request.setAttribute(Constants.KEY_REQUEST_RESULT, page);			
		}catch (Exception e) {
			forward = doException( request, e,forward);
		}
		return mapping.findForward(forward);
	}
	
	public ActionForward manage8(ActionMapping mapping, ActionForm actionForm, HttpServletRequest request, HttpServletResponse response) {
		log.debug("修改密码");
		return mapping.findForward("manage8");
	}
	
	public ActionForward changePassword(ActionMapping mapping, ActionForm actionForm, HttpServletRequest request, HttpServletResponse response) {
		log.debug("提交修改密码");
		String forward = "listProducts";
		CompanyBlogic blogic = new CompanyBlogic();
		try {
			blogic.changePassword(request.getParameter("userId"), request.getParameter("oldPassword"), request.getParameter("newPassword"));
			log.debug("密码已修改" );
			// 返回成功的显示信息，需要在结果页面添加 <mytag:MyActionMsg />
	        request.setAttribute(Constants.MSGKEY, new MsgKey("","密码已修改"));
		}catch (Exception e) {
			forward = doException( request, e, forward);
		}
		
		return mapping.findForward("manage8");
	}


}
